package com.fiberhome.opticalbox.ui.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.BaseFragment;
import com.fiberhome.opticalbox.C;
import com.fiberhome.opticalbox.common.upgrade.UpgradeService;
import com.fiberhome.opticalbox.ui.HelpActivity;
import com.fiberhome.opticalbox.utils.FileUtil;
import com.fiberhome.opticalbox.utils.LogUtil;
import com.fiberhome.opticalbox.view.TitleView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class AboutFragment extends BaseFragment {

	private TitleView titleView;
	private Dialog dlgVersion;

	private ImageView imgUpgrade;

	static class AppInfo {
		int versionCode;
		String upgradeInfo;
	}

	private AppInfo appInfo;
	private int versionCode;

	@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ob_fragment_about, null);

		titleView = (TitleView) view.findViewById(R.id.ob_titleView);
		titleView.setTitle(R.string.ob_about);
		titleView.setBackground(R.drawable.ob_bg_title);
		titleView.addLeftDrawableMenu(holder, R.drawable.ob_ico_back, 15, 25, onMainBackClickListener);

		view.findViewById(R.id.lay_share_wechat).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_feedback).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_help).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_version_check).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_qr_code).setOnClickListener(onClickListener);

		imgUpgrade = (ImageView) view.findViewById(R.id.img_upgrade);

		view.findViewById(R.id.lay_feedback).setVisibility(View.GONE);

		try {
			PackageInfo info = holder.getPackageManager().getPackageInfo(holder.getPackageName(), 0);
			versionCode = info.versionCode;

			TextView txVersion = (TextView) view.findViewById(R.id.tx_version);
			txVersion.setText(info.versionName);
		} catch (Exception e) {
			versionCode = 1;
		}

		return view;
	}

	private void requestVersionInfo() {
		if (holder != null) {
			RequestQueue requestQueue = Volley.newRequestQueue(holder);
			StringRequest request = new StringRequest(C.app.versionAddress, new Listener<String>() {
				@Override public void onResponse(String response) {
					imgUpgrade.setVisibility(View.GONE);

					Gson gson = new Gson();
					try {
						appInfo = gson.fromJson(new String(response.getBytes("ISO8859-1")), AppInfo.class);
					} catch (JsonSyntaxException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}

					showVersionInfo();
				}
			}, new ErrorListener() {
				@Override public void onErrorResponse(VolleyError error) {
					LogUtil.e("AboutFragment get version fail");
					showToast(R.string.ob_upgrade_fail);
					imgUpgrade.setVisibility(View.GONE);
				}
			});
			requestQueue.add(request);

		}
	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override public void onClick(View view) {
			switch (view.getId()) {
			case R.id.lay_share_wechat:
				shareWechat();
				break;
			case R.id.lay_feedback:
				// function removed
				break;
			case R.id.lay_help:
				help();
				break;
			case R.id.lay_version_check:
				versionCheck();
				break;
			}
		}
	};

	private void versionCheck() {
		if (appInfo == null) {
			imgUpgrade.setVisibility(View.VISIBLE);
			requestVersionInfo();
		} else {
			showVersionInfo();
		}
	}

	private void showVersionInfo() {
		if (appInfo.versionCode > versionCode) {
			dlgVersion = dialogUtil.createSimple(appInfo.upgradeInfo, true, true).setTitleText(R.string.ob_upgrade_1)
					.setConfirmListener(new OnClickListener() {
						@Override public void onClick(View v) {
							if (holder != null) {
								Intent intent = new Intent(holder, UpgradeService.class);
								intent.putExtra("Key_App_Name", getString(R.string.ob_app_name));
								intent.putExtra("Key_Down_Url", C.app.speedTestAddress);
								holder.startService(intent);
							}
							dlgVersion.dismiss();
						}
					}).show();

		} else {
			showToast(R.string.ob_upgrade_2);
		}
	}

	private void shareWechat() {
		if (holder != null) {
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			List<ResolveInfo> resInfo = holder.getPackageManager().queryIntentActivities(intent, 0);
			boolean find = false;

			if (!resInfo.isEmpty()) {
				for (ResolveInfo info : resInfo) {
					ActivityInfo activityInfo = info.activityInfo;
					if (activityInfo.packageName.contains("com.tencent.mm") && activityInfo.name.contains("com.tencent.mm")) {
						intent.setAction(Intent.ACTION_SEND);
						intent.setType("image/*");
						intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
						intent.putExtra("Kdescription", "烽火路由助手");
						intent.putExtra(Intent.EXTRA_SUBJECT, "分享");

						try {
							InputStream in = holder.getAssets().open("ob_app_qr_code.png");
							File f = new FileUtil().writeToSDCard("fh.box", "rqCode.png", in);
							intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
						} catch (IOException e) {
							LogUtil.e("二维码获取失败");
						}

						intent.setClassName(activityInfo.packageName, activityInfo.name);

						find = true;
						break;
					}
				}
				if (find) {
					startActivity(intent);
				} else {
					showToast(R.string.ob_share_1);
				}
			}
		}
	}

	private void help() {
		actionStart(HelpActivity.class);
	}

	public static boolean saveBitmap2File(Bitmap bmp, String filename) {
		CompressFormat format = Bitmap.CompressFormat.JPEG;
		int quality = 100;
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(filename);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}

		return bmp.compress(format, quality, stream);
	}
}
